package com.lagou.edu.boss.service.impl;

import com.lagou.edu.boss.service.ICourseService;
import com.lagou.edu.common.constant.MQConstant;
import com.lagou.edu.common.mq.RocketMqService;
import com.lagou.edu.common.mq.dto.BaseMqDTO;
import com.lagou.edu.course.api.CourseRemoteService;
import com.lagou.edu.course.api.dto.CourseDTO;
//import com.lagou.edu.message.api.dto.CourseStatusReleaseDTO;
import org.apache.commons.lang.StringUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Author:   mkp
 * Date:     2020/6/27 15:06
 * Description: 课程
 */
@Service
public class CourseService implements ICourseService {

    public final static String host_prefix = "http://www.lgstatic.com/";
    public final static String https_host_prefix = "https://www.lgstatic.com/";

    @Autowired
    private CourseRemoteService courseRemoteService;

    //@Autowired
    //private RocketMqService rocketMqService;

    @Override
    public void removeImgWidthAttribute(Element element) {
        if (element.tagName().equals("img")) {

            String attr = element.attr("src");
            if (StringUtils.isNotEmpty(attr) && !attr.startsWith(host_prefix) && !attr.startsWith(https_host_prefix)) {
                throw new RuntimeException("图片未完全保存成功！");
            }

            element.attr("width", "100%");
            element.attr("height", "100%");
        }
        Elements childs = element.select("> *");
        if (childs != null && !childs.isEmpty()) {
            for (Element child : childs) {
                removeImgWidthAttribute(child);
            }
        }
    }

    @Override
    public boolean changeState(Integer courseId, Integer status) {
        //用Feign调用课程服务的上下架接口
        boolean res = courseRemoteService.changeState(courseId, status);
        CourseDTO courseDTO = courseRemoteService.getCourseById(courseId);
        //用RocketMQ调用消息服务进行消息推送
        if(status.equals(1) && res) {//发送消息通知
            //rocketMqService.convertAndSend(MQConstant.Topic.COURSE_STATUS_RELEASE, new BaseMqDTO<CourseStatusReleaseDTO>(new CourseStatusReleaseDTO(courseDTO.getId()), UUID.randomUUID().toString()));
        }
        return false;
    }
}
